package wang.filter;

import wang.bean.Admin;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter", urlPatterns = "/*")
public class LoginFilter implements Filter {
  public void init(FilterConfig config) throws ServletException {
  }

  public void destroy() {
  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
    String path = ((HttpServletRequest) request).getServletPath();
    if (!(path.startsWith("/css") || path.startsWith("/js") || path.startsWith("/bootstrap") || path.startsWith("/images") || path.equals("/favicon.ico"))) {
      System.out.println(path);
    }
    HttpSession session = ((HttpServletRequest) request).getSession();
    Admin admin = (Admin) session.getAttribute("admin");
    // 如果当前访问的页面是网站入口页面||当前访问的页面是管理员登录页面||当前访问的页面是游客页面，直接放行
    // 否则，判断管理员是否已经登录
    if (path.equals("/entrance.jsp") || path.equals("/login.jsp") || path.equals("/tourist.jsp")) {
      chain.doFilter(request, response);
    } else if (path.startsWith("/css") || path.startsWith("/js") || path.startsWith("/bootstrap") || path.startsWith("/images") || path.equals("/favicon.ico")) {
      // 如果是静态资源，则直接放行，否则会出现资源无法访问导致页面样式错乱的问题
      chain.doFilter(request, response);
    } else if (path.equals("/login.admin") || path.equals("/register.admin")) {
      // 如果管理员已经登录，或者当前请求登录或注册接口，也放行
      chain.doFilter(request, response);
    } else if (admin != null) {
      chain.doFilter(request, response);
    } else {
      // 如果是其他请求，则跳转到登录页面
      response.getWriter().write("<script>window.location.href='entrance.jsp';</script>");
    }
  }
}
